/* Macro Purpose: Creates a downsampled stack of images from all RAW
 *                images in a dir (passed in as an arg).
 *                It does this by opening each img, downsampling them,
 *                and then saving them all as a zip'd stack.
 *                
 * Parameters (as one str): 1:Debug (boolean indicating if this macro should print status, etc)
 *                          2:Path of images dir.  3:Path to result dir  4:Result img name
 *                          5:Scale to downsample by (2 means downsample to 1/2 orig dimensions)
 *                          Others: RAW params (in order listed below)             
 */

argsStr = getArgument();  // try to get arg passed in by user
if(argsStr == "") {
	print("\nNo argument string passed to this macro. Exiting now.\n");
	exit;
}
debugIt = false;
// Print str if in Debug mode
function printD(str) { 
  if(debugIt) print(str);	
} // end function printD() /////
//////////////////////////////////////////////////////////////////////////////
/// CONSTANTS & PARAMS (most get overridden by passed-in vals) ///////////////
arg_delimeter = "@"; // the delimeter used to seperate args in the single arg str passed in
file_extension_to_open = ".f32";

saveImgPath = "/home/jfrank3/www-home/imagerecon/Images/";
saveImgName = "stack_from_resampled_RAW.zip";
//saveImgType = "Tiff";
saveImgType = "ZIP";

// Raw opening paramaters - examples and order of args listed below - vals will be overridden by passed-in vals
rawImgType = "32-bit Real";
rawWidth   = 560;
rawHeight  = 560;
rawOffset  = 0;
rawNumImgs = 1;
rawGapBetweenImgs = 0;

scale = 2;  // the ratio to downsample by (scale=4 means resample to 1/4 size)
//// end Constants & Params //////////////////////
//////////////////////////////////////////////////

argsArray = split(argsStr, arg_delimeter); // split str on delimeter
// Break out the appropriate params from the argArray
debugIt     = argsArray[0];
pathToImg   = argsArray[1];
saveImgPath = argsArray[2];
saveImgName = argsArray[3];
scale       = argsArray[4];

rawImgType  = argsArray[5];
rawWidth    = argsArray[6];
rawHeight   = argsArray[7];
rawOffset   = argsArray[8];
rawNumImgs  = argsArray[9];
rawGapBetweenImgs = argsArray[10];
// NOTE:  In the Open, add the boolean directive arg: "little-endian" for these "f32" images



// Trying to fix the Little-Endian issue by making saves also use Little-Endian
// the "save" option enables "Save TIFF and Raw in Intel Byte Order", which saves using little-endian byte order
//run("Input/Output...", "jpeg=75 gif=-1 file=.txt save copy_row save_column save_row"); 



// Get a list of all files in dir
images_to_open = getFileList(pathToImg);

///// DEBUGGING STATEMENT ////
printD("\nYou passed into this macro args: "); 
for(i=0; i < argsArray.length; i++) {
	printD("\"" + argsArray[i] + "\"");
}


// Open all imgs
openStrSecondHalf = "image=[" + rawImgType + "] "
		               + "width="   + rawWidth   + " height=" + rawHeight + " offset=" + rawOffset
		               + " number=" + rawNumImgs + " gap="    + rawGapBetweenImgs
		               + " little-endian";

printD("2nd part of open str: \"" + openStrSecondHalf + "\"");		                   


for( i = 0; i < images_to_open.length; i++ ) {
	if(endsWith(images_to_open[i], file_extension_to_open)) {
		// Import the raw file
			//run("Raw...", "open=[" + pathToImg + images_to_open[i] +"] image=[16-bit Unsigned] width=1024 height=768 offset=0 number=1 gap=0");
		//run("Raw...", "open=[" + pathToImg + images_to_open[i] +"] image=[" + rawImgType + "] "
		//                   + "width="   + rawWidth   + " height=" + rawHeight + " offset=" + rawOffset
		//                   + " number=" + rawNumImgs + " gap="    + rawGapBetweenImgs
		//                   + " little-endian");
		printD("About to open raw img with str: \n\"" 
		         + "open=[" + pathToImg + images_to_open[i] +"] " + openStrSecondHalf + "\"");
		
		run("Raw...", "open=[" + pathToImg + images_to_open[i] +"] " + openStrSecondHalf );

		//saveAs(saveImgType, saveImgPath + "convertedF32_" + i + ".zip" );
	}
}
/*
// Downsample imgs (in prep of sending the stack to the client for previewing)
for( i = 0; i < images_to_open.length; i++ ) {
	if(endsWith(images_to_open[i], file_extension_to_open)) {
		selectWindow(images_to_open[i]);
		      //run("Resample", "factor=4 factor=4 factor=4");

		// Need to convert from 32-bit to 16-bit in order for Resample command to work on these 32-bit imgs
		run("16-bit");
		      
		run("Resample", "factor=" + scale + " factor=" + scale + " factor=" + scale);
	}
}

// Create the stack from all open images - first close the orig (full-sized) img windows so we don't stack them
for( i = 0; i < images_to_open.length; i++ ) {
	if(endsWith(images_to_open[i], file_extension_to_open)) {
		selectWindow(images_to_open[i]);
		close();
	}
}
*/
run("Images to Stack", "name=[] title=[] use keep");

saveAs(saveImgType, saveImgPath + saveImgName );

printD("Macro finished saving images to: \"" + saveImgPath + "\"");
